<template>
  <div class="happy8">
    <el-form
      @submit.prevent="onSubmit"
      :inline="true"
      :model="formData"
      :rules="rules"
      class="demo-form-inline"
    >
      <el-form-item>
        <el-input
          v-model="formData.luckyNumber"
          placeholder="请输入想要搜索的号码"
          clearable
          @keyup.enter="onSubmit"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
      <el-form-item>
        <span class="red">{{ `共${tableData.length}注` }}</span>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
      <el-table-column align="center" prop="code" label="期数" width="158" />
      <el-table-column align="center" prop="red" label="开奖结果">
        <template v-slot="{ row }">
          <span class="red">{{ punctuationDisplace([','], row.red, ' ') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="date" label="日期" width="158" />
      <el-table-column align="center" prop="content" label="中奖地区" width="158" />
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const formData = ref({
  luckyNumber: '',
})
const rules = reactive({
  luckyNumber: [
    { min: 1, max: 20, message: '搜索的号码应该1~20个之间', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          return callback(new Error('请输入想要搜索的号码'))
        }
      },
      trigger: 'blur',
    },
  ],
})

const tableData = ref([])
const loading = ref(false)

onMounted(() => {
  tableData.value = JSON.parse(localStorage.getItem('happy8List'))
})

const onSubmit = () => {
  if (!formData.value.luckyNumber) {
    return (tableData.value = JSON.parse(localStorage.getItem('happy8List')))
  }

  loading.value = true
  const luckyNumber = punctuationDisplace(
    ['，', ',', ', ', '、', ' '],
    formData.value.luckyNumber,
    ',',
  )
    ?.split(',')
    ?.filter(Boolean)
    ?.map((item) => (item.length === 1 ? `0${item}` : item))

  const luckyList = JSON.parse(localStorage.getItem('happy8List')).filter((item) => {
    return isSubset(item.luckyNumber, luckyNumber)
  })
  if (luckyList.length !== 0) {
    tableData.value = luckyList
  } else {
    ElMessage.error('该号码暂未开出一等奖')
  }

  loading.value = false
}

// 判断数组parentArr是否全部包含数组subsetArr
const isSubset = (parentArr, subsetArr) => {
  const parentSet = new Set(parentArr)
  return subsetArr.every((item) => parentSet.has(item))
}

// 全部替换字符
const punctuationDisplace = (arr, str, replace) => {
  let nowStr = str

  arr.forEach((find) => {
    nowStr = nowStr.replace(new RegExp(find, 'g'), replace)
  })
  return nowStr
}
</script>

<style lang="scss" scoped>
::v-deep .el-input__wrapper {
  width: 188px;
}
.red {
  color: #e74c3c;
}
</style>
